import { Module } from 'vuex'
import UserStateTypes from './types'
import RootStateTypes from '../../types'
import {loginApi,refreshTokenApi} from '@/request/user'
import {menuTreeApi} from '@/request/menu'
import {ElMessage} from 'element-plus'
import {setToken,getToken,removeToken} from '@/utils/auth'
// Create a new store Modules.
const userModule: Module<UserStateTypes, RootStateTypes> = {
  namespaced: true,
  state: {
    token: getToken() || '',
    refresh_token: '',
    uid:Number(localStorage.getItem('uid')) || 0,
    menuTree:[],
  },
  mutations: {
    login_success:(state,{token,refresh_token,uid})=>{
      state.token = token
      state.refresh_token = refresh_token,
      state.uid = uid
      //uid
      localStorage.setItem('uid',uid)
      //存token
      setToken(token)
    },
    // 获取资源菜单
    get_menu:(state,menuArr:any[])=>{
      state.menuTree = menuArr
      console.log(state.menuTree);

    },
    login_out:(state) => {
      state.token = ''
      state.refresh_token = ''
      state.menuTree = [],
      state.uid = 0
    },
    refresh_token:(state,{token,refresh_token})=>{
      state.token = token
      state.refresh_token = refresh_token

      //存token
      setToken(token)
    }
  },
  actions: {
    // 登录
    login: ({ commit }, postData) => {
      return new Promise(async (resolve, reject) => {
        const res = await loginApi(postData)
        if (res.data.code === 1) {
            commit("login_success", {
                token: res.data.data.token,
                refresh_token: res.data.data.refresh_token,
                uid: res.data.data.uid,
            });
        } else {

        }
        resolve(res);
      })
    },
    // 获取资源菜单
    getMenuTree: async ({ commit },toIndex?:Function) => {
      const res = await menuTreeApi()
        if (res.data.code === 1) {
            commit("get_menu", res.data.data);
            toIndex && toIndex()
        } else {
          ElMessage({
            message:"获取资源菜单失败",
            type:"error"
          })
        }
    },
    // 退出登录
    logout:({ commit })=>{
      removeToken()
      commit('login_out')
    },
    // 刷新token
    refreshToken:async ({commit},data) => {
      const res = await refreshTokenApi(data)
      if(res.data.code === 1){
        commit('refresh_token',res.data.data)
      }
    }
  }
}

export default userModule
